﻿using Furion.DependencyInjection;
using Mapster;
using Queer.Entity.SystemManage;
using Queer.Enum;
using Queer.IService.SystemManage;
using Queer.Model.Result.SystemManage;
using Queer.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Queer.Cache
{
    public class MenuCache : ITransient
    {
        private readonly string _menuCacheKey = CacheKeys.MenuCache.ParseToString();

        private readonly ICache _cache;
        private readonly IMenuService _menuService;

        public MenuCache(Func<string, ISingleton, object> resolveNamed, IMenuService menuService)
        {
            _cache = resolveNamed(GlobalContext.SystemConfig.CacheService, default) as ICache;
            _menuService = menuService;
        }


        public async Task<List<MenuEntity>> GetMenuCacheList()
        {
            var cacheList = _cache.Get<List<MenuEntity>>(_menuCacheKey);
            if (cacheList == null || cacheList.Count() == 0)
            {
                // 采用DTO模型，减少不必要的字段进入缓存
                cacheList = await _menuService.GetList(null);
                _cache.Set(_menuCacheKey, cacheList.Adapt<List<MenuCacheModel>>());
            }

            return cacheList;
        }

        public void Remove()
        {
            _cache.Remove(_menuCacheKey);
        }
    }
}